package org.zoomdev.zoom.web.parameter;

import org.zoomdev.zoom.common.utils.Classes;
import org.zoomdev.zoom.web.action.ActionContext;

import java.lang.reflect.Type;

public final class ParameterParser {

    private static final Object[] EMPTY = Classes.EMPTY;
    private final String[] names;
    private final Type[] types;
    @SuppressWarnings("rawtypes")
    private final ParameterAdapter[] adapters;


    //private final Config[] configs;


    @SuppressWarnings("rawtypes")
    public ParameterParser(
            String[] names,
            Type[] types,
            ParameterAdapter[] adapters) {
        this.names = names;
        this.types = types;
        this.adapters = adapters;
//
//        int c = names.length;
//        this.configs = new Config[c];
//
//        for (int i = 0; i < c; ++i) {
//            this.configs[i] = new Config(adapters[i], names[i], types[i]);
//        }
    }

    class Config {
        final ParameterAdapter adapter;

        final String name;
        final Type type;

        Config(ParameterAdapter adapter, String name, Type type) {
            this.adapter = adapter;
            this.name = name;
            this.type = type;
        }


        Object call(ActionContext context) {
            return adapter.get(context, name, type);
        }
    }

//    public Object[] parse2(ActionContext context) throws Exception {
//        final Config[] configs = this.configs;
//        int c = configs.length;
//        if (c == 0) {
//            return EMPTY;
//        }
//        Object[] args = new Object[c];
//        for (int i = 0; i < c; ++i) {
//            args[i] = configs[i].call(context);
//        }
//        return args;
//    }

    @SuppressWarnings("unchecked")

    public Object[] parse(ActionContext context) throws Exception {
        final String[] names = this.names;
        int c = names.length;
        if (c == 0) {
            return EMPTY;
        }
        final ParameterAdapter[] adapters = this.adapters;
        final Type[] types = this.types;
        Object[] args = new Object[c];
        for (int i = 0; i < c; ++i) {
            args[i] = adapters[i].get(context, names[i], types[i]);
        }
        return args;
    }
}
